package com.ruoyi.web.service;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.temporal.WeekFields;
import java.util.*;

@Service
public class C2VersionInfoService {
    @Autowired
    private DruidDataSource druidDataSource;

    public Map<String, Object> getC2VersionInfoByPeriods() {
        // 创建返回数据的结构
        Map<String, List<String>> timePeriods = new HashMap<>();
        Map<String, List<Integer>> statuses = new HashMap<>();
        Map<String, List<Integer>> releaseStatuses = new HashMap<>();
        Map<String, List<Integer>> pubStatuses = new HashMap<>();

        String sql = "SELECT `buildTime`, COALESCE(`status`, 0) AS `status`, " +
                "COALESCE(`releaseStatus`, 0) AS `releaseStatus`, " +
                "COALESCE(`pubStatus`, 0) AS `pubStatus` FROM `c2_version_info`;";
        System.out.println("Executing SQL: " + sql);

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            // 使用多个 Map 分别按周期分组统计
            Map<String, Map<String, Integer>> weeklyStatsMap = new TreeMap<>();
            Map<String, Map<String, Integer>> monthlyStatsMap = new TreeMap<>();
            Map<String, Map<String, Integer>> quarterlyStatsMap = new TreeMap<>();
            Map<String, Map<String, Integer>> yearlyStatsMap = new TreeMap<>();

            while (rs.next()) {
                // 使用 LocalDateTime 获取 buildTime
                LocalDateTime buildTime = rs.getObject("buildTime", LocalDateTime.class);
                int status = rs.getInt("status");
                int releaseStatus = rs.getInt("releaseStatus");
                int pubStatus = rs.getInt("pubStatus");

                // 获取各周期时间段
                String week = getWeekPeriod(buildTime);
                String month = getMonthPeriod(buildTime);
                String quarter = getQuarterPeriod(buildTime);
                String year = getYearPeriod(buildTime);

                // 按周期统计
                updateStats(weeklyStatsMap, week, status, releaseStatus, pubStatus);
                updateStats(monthlyStatsMap, month, status, releaseStatus, pubStatus);
                updateStats(quarterlyStatsMap, quarter, status, releaseStatus, pubStatus);
                updateStats(yearlyStatsMap, year, status, releaseStatus, pubStatus);
            }


            // 转换统计数据到最终结构
            processStats(weeklyStatsMap, "week", timePeriods, statuses, releaseStatuses, pubStatuses);
            processStats(monthlyStatsMap, "month", timePeriods, statuses, releaseStatuses, pubStatuses);
            processStats(quarterlyStatsMap, "quarter", timePeriods, statuses, releaseStatuses, pubStatuses);
            processStats(yearlyStatsMap, "year", timePeriods, statuses, releaseStatuses, pubStatuses);

        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 返回包含所有需要的数据
        Map<String, Object> response = new HashMap<>();
        response.put("timePeriods", timePeriods);
        response.put("statuses", statuses);
        response.put("releaseStatuses", releaseStatuses);
        response.put("pubStatuses", pubStatuses);

        return response;
    }

    // 更新统计数据
    private void updateStats(Map<String, Map<String, Integer>> statsMap, String periodKey,
                             int status, int releaseStatus, int pubStatus) {
        statsMap.putIfAbsent(periodKey, new HashMap<>());
        Map<String, Integer> periodStats = statsMap.get(periodKey);

        periodStats.put("statusCount", periodStats.getOrDefault("statusCount", 0) + status);
        periodStats.put("releaseStatusCount", periodStats.getOrDefault("releaseStatusCount", 0) + (releaseStatus == 1 ? 1 : 0));
        periodStats.put("pubStatusCount", periodStats.getOrDefault("pubStatusCount", 0) + (pubStatus == 1 ? 1 : 0));
    }

    // 处理统计数据并存入最终的返回结构
    private void processStats(Map<String, Map<String, Integer>> statsMap, String periodKey,
                              Map<String, List<String>> timePeriods, Map<String, List<Integer>> statuses,
                              Map<String, List<Integer>> releaseStatuses, Map<String, List<Integer>> pubStatuses) {
        List<String> periods = new ArrayList<>();
        List<Integer> statusCounts = new ArrayList<>();
        List<Integer> releaseStatusCounts = new ArrayList<>();
        List<Integer> pubStatusCounts = new ArrayList<>();

        // 获取并排序时间段
        List<String> sortedPeriods = new ArrayList<>(statsMap.keySet());

        // 自定义排序逻辑：如果 periodKey 是 week，按 -W 后的数字升序排序
        if ("week".equals(periodKey)) {
            sortedPeriods.sort((p1, p2) -> {
                int week1 = extractWeekNumber(p1);
                int week2 = extractWeekNumber(p2);
                return Integer.compare(week1, week2);
            });
        } else {
            // 默认按自然顺序排序（时间升序）
            Collections.sort(sortedPeriods);
        }

        // 填充对应的数据
        for (String period : sortedPeriods) {
            periods.add(period);
            Map<String, Integer> periodStats = statsMap.get(period);
            statusCounts.add(periodStats.getOrDefault("statusCount", 0));
            releaseStatusCounts.add(periodStats.getOrDefault("releaseStatusCount", 0));
            pubStatusCounts.add(periodStats.getOrDefault("pubStatusCount", 0));
        }

        // 将排序后的结果存入最终的返回结构
        timePeriods.put(periodKey, periods);
        statuses.put(periodKey, statusCounts);
        releaseStatuses.put(periodKey, releaseStatusCounts);
        pubStatuses.put(periodKey, pubStatusCounts);
    }

    // 提取 -W 后的数字
    private int extractWeekNumber(String period) {
        int index = period.indexOf("-W");
        if (index != -1) {
            try {
                return Integer.parseInt(period.substring(index + 2));
            } catch (NumberFormatException e) {
                // 如果解析失败，返回一个较大值以保证错误值排在最后
                return Integer.MAX_VALUE;
            }
        }
        return Integer.MAX_VALUE; // 如果没有 -W，返回一个较大值
    }


    // 获取周期的时间段（以周为例）
    private String getWeekPeriod(LocalDateTime buildTime) {
        WeekFields weekFields = WeekFields.of(Locale.getDefault());
        int weekOfYear = buildTime.get(weekFields.weekOfWeekBasedYear());
        int year = buildTime.getYear();
        return year + "-W" + weekOfYear;
    }


    // 获取月度周期
    private String getMonthPeriod(LocalDateTime buildTime) {
        int year = buildTime.getYear();
        int month = buildTime.getMonthValue();
        return String.format("%d-%02d", year, month); // 格式化为 yyyy-MM
    }


    // 获取季度周期
    private String getQuarterPeriod(LocalDateTime buildTime) {
        int month = buildTime.getMonthValue();
        int quarter = (month - 1) / 3 + 1; // 计算季度
        int year = buildTime.getYear();
        return year + "-Q" + quarter;
    }

    // 获取年度周期
    private String getYearPeriod(LocalDateTime buildTime) {
        return String.valueOf(buildTime.getYear());
    }
}